# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import base64
import requests
from flask import jsonify, Blueprint, request, current_app

import backend.user.v2.utils
from backend.tools.dw_token import user_token_required, user_authorization
from backend.tools.user_decorator import (
    check_values,
    decorator_user_exception,
    return_status_succeed,
)
from backend.exceptions import PLExceptionTuple, PLException, APIException
from backend.statistics import counter_sent
from backend.wallet_manager import transaction_sent
from ..business_service import DetectRequest, Display
from ..utils import get_business_service_by_id
from backend.wallet_manager import utils as wallet_utils


business_service_blueprint = Blueprint("business_service", __name__)


# 商品识别
@business_service_blueprint.route(
    "/recognition/<business_service_id>", methods=["POST"]
)
@decorator_user_exception
def recognition(**kwargs):
    if "user" not in kwargs:
        user = backend.user.v2.utils.create_visitor()
    business_service_id = kwargs["business_service_id"]
    source_type = request.args.get("source_type", "unknown")
    #  recognition_price 需要通过数据库取值得到，目前写死
    recognition_price = 0.2
    if user and user.type == "user":
        user_left_amount = wallet_utils.get_wallet_balance_by_user_id(user.id).left_amount
        if user_left_amount < recognition_price:
            raise APIException(message=u"余额不足扣费失败")

    # 业务服务请求计数触发
    business_service = get_business_service_by_id(business_service_id)
    counter_sent.send(
        current_app._get_current_object(),
        service=business_service,
        counter=["call_total", "current_month_call"],
    )
    result = return_status_succeed()
    body = check_values(request, ["image_url"])

    # 图像URL
    try:
        response = requests.get(body["image_url"])
        image = "data:image/jpeg;base64," + base64.b64encode(
            response.content
        ).decode("ascii")
    except Exception:
        counter_sent.send(
            current_app._get_current_object(),
            service=business_service,
            counter="call_failed",
        )
        raise APIException(message=u"图片下载失败")

    # 商品识别
    detect_request = DetectRequest(user.id, business_service_id, img_width=body.get("width", 0), img_height=body.get("height", 0,))
    business_request_id = detect_request.business_request.id
    try:
        detect_request.save_img_url(body["image_url"])
        detect_request.save_source_type(source_type)
        detect_request.detect(image=image)
    except PLExceptionTuple as e:
        detect_request.save_request_failed()
        counter_sent.send(
            current_app._get_current_object(),
            service=business_service,
            counter="call_failed",
        )
        raise e
    detect_display = Display(detect_request)
    try:
        result["data"] = detect_display.data
    except PLExceptionTuple as e:
        counter_sent.send(
            current_app._get_current_object(),
            service=business_service,
            counter="call_failed",
        )
        raise e

    counter_sent.send(
        current_app._get_current_object(), service=business_service, counter="call_done"
    )
    if detect_request.business_request_log.should_pay():
        transaction_sent.send(
            current_app._get_current_object(),
            service=business_service,
            business_request_id=business_request_id,
            token=request.headers.get("Authorization"))

    return jsonify(result)
